<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="90%" :showOkBtn="false">

    <vxe-grid ref="tableRef" v-bind="gridOptions" :style="{height: (contentHeight*0.85)+'px'}">
      <template #toolbar_buttons>
        <vxe-button type="submit" status="success" content="导出勾选订单数据" @click="createOrderTempleFn" style="margin-left: 5px;" :loading="loading"></vxe-button>

      </template>

    </vxe-grid>


  </BasicDrawer>
</template>
<script lang="ts" setup>
import {ref, computed, unref, reactive} from 'vue';
import { BasicForm, useForm, ApiSelect } from '@/components/Form';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import util from "@/utils/util";

import { useMessage } from "@/hooks/web/useMessage";
import { useUserStore } from "@/store/modules/user";
import {BasicTableProps, VxeTableDefines} from "@/components/VxeTable";
import {itemColumns, orderColumns, vxeTableColumns} from './role.data';
import { yiTiaoZhengList,createOrderTemple} from "@/api/heng/dkn";
import axios from 'axios';
import {useGlobSetting} from "@/hooks/setting";
const userStore = useUserStore();
const loading = ref(false);

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const dataList = ref({});
const { createMessage } = useMessage();
const contentHeight = ref(window.innerHeight);

const id = ref("");

const tableRef = ref();


const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // setDrawerProps({ confirmLoading: false });
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  // if (unref(treeData).length === 0) {
  //   treeData.value = (await getMenuList()) as any as TreeItem[];
  // }
  isUpdate.value = !!data?.isUpdate;
  id.value = "";
  dataList.value=data;
  tableRef.value.commitProxy('reload');

});

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: orderColumns,
  filterConfig: {
    remote: true,
  },
  exportConfig:{},
  showFooter: true,

  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
  },
  formConfig: {
    enabled: false,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
    },
  },
});



function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = dataList.value;
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field ] = value;
    });
  }
 // console.log("----json:", json);
  // ywApproveList xftList
  return yiTiaoZhengList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}






const getTitle = computed(() => (!unref(isUpdate) ? '销售订单导入模板' : '销售订单导入模板'));

function createOrderTempleFn(){
  let selectRows = tableRef.value.getCheckboxRecords();

  if (!selectRows.length) {
    createMessage.error('请先勾选物料!');
    return false;
  }
  createOrderTempleSubFn(selectRows)

}


const globSetting = useGlobSetting();

function  createOrderTempleSubFn(postData){
  loading.value = true;
  createOrderTemple(postData).then(res => {
    if(res.code==200){
      if(res.data){
        window.open(res.data, "_blank");

      }
    }else{
      createMessage.error(res.message);
    }
  }).finally(()=>{
    loading.value = false;
  })
}

// 导出Excel的请求函数 旧
const exportExcel = async (postData) => {
  try {
    const urlPrefix = globSetting.urlPrefix;
    // console.log("urlPrefix"+ urlPrefix)
    loading.value = true;
    // 1. 发送POST请求，关键配置responseType: 'blob'
    const response = await axios({
      url: '/hl/excel/createOrderTemple', // 后端接口地址（与Spring Boot接口对应）
      method: 'POST',
      data: postData, // 前端传递的JSON数据（如{fileName: "用户表", dataList: [...]}）
      responseType: 'blob', // 关键：指定响应为二进制流（Blob）
      headers: {
        'Content-Type': 'application/json', // 告诉后端请求体是JSON
      },
    });

    // 2. 处理响应，触发下载
    handleExcelDownload(response);
    loading.value = false;
    return true; // 下载成功返回
  } catch (error) {
    console.error('Excel导出失败：', error);
    alert('导出失败，请重试');
    return false; // 下载失败返回
  }
};


// 处理Excel下载的工具函数
const handleExcelDownload = (response) => {
  // 3. 从响应头获取文件名（后端若设置了Content-Disposition）
  const disposition = response.headers['content-disposition'];
  let fileName = '销售订单导入模板.xlsx'; // 默认文件名

  if (disposition) {
    // 解析后端返回的文件名（格式：attachment; filename="xxx.xlsx"）
    const match = disposition.match(/filename="?([^";]+)"?/);
    if (match && match[1]) {
      // 解码文件名（处理中文乱码）
      fileName = decodeURIComponent(match[1]);
    }
  }

  // 4. 将响应数据（Blob）转为下载链接
  const blob = new Blob([response.data], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // Excel的MIME类型
  });
  const url = URL.createObjectURL(blob);

  // 5. 创建临时<a>标签触发下载
  const a = document.createElement('a');
  a.href = url;
  a.download = fileName; // 设置下载文件名
  document.body.appendChild(a);
  a.click(); // 模拟点击下载

  // 6. 清理临时资源，避免内存泄漏
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

</script>
